package com.sjk.flink.schema;

import com.fasterxml.jackson.databind.JsonNode;
import networknt.schema.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.Set;

public class TimelinessValidator extends BaseJsonValidator {
    private static final Logger logger = LoggerFactory.getLogger(TimelinessValidator.class);
    private static final String TIMELINESS = "timeliness";

    //private static JsonNode schemaNode;

    public TimelinessValidator(String schemaPath, JsonNode schemaNode, JsonSchema parentSchema, ValidationContext validationContext, ValidatorTypeCode type) {
        super(schemaPath, schemaNode, parentSchema, type, validationContext);
        //this.schemaNode = schemaNode;
        this.validationContext = validationContext;
        parseErrorCode(getValidatorType().getErrorCodeKey());
    }

    @Override
    public Set<ValidationMessage> validate(JsonNode node, JsonNode rootNode, String at) {
        debug(logger, node, rootNode, at);
        Set<ValidationMessage> errors = new LinkedHashSet<>();
        JsonType nodeType = TypeFactory.getValueNodeType(node, this.validationContext.getConfig());
        System.out.println("node >>>>>>>>>>>>>>>>  "+node);
        if (nodeType != JsonType.STRING) {
            return errors;
        }
        //待检查数据
        String checkVal = node.asText();
        System.out.println("待检查数据 >>>>>>>>>>>>>>>>  " + checkVal);
        //
        String parm = schemaNode.asText();
        System.out.println(">>>>>>>>>>>>>>    "+parm);
        String[] args = parm.split(",");
        //比较字段
        String compareFeild = args[0];
        System.out.println("compareFeild >>>>>>>>>>>>>>    "+compareFeild);
        //超时时间
        int expireTime = 24;
        //误差时间
        long mistakeTime = 3600000;

        if (args.length == 2) {
            expireTime = Integer.parseInt(args[1]);
        } else if (args.length == 3) {
            mistakeTime = Long.parseLong(args[2]);
        }
        boolean valid = false;
        JsonNode compareNode = rootNode.get(compareFeild);
        if (compareNode == null) {
            errors.add(buildValidationMessage(at, "过期检查失败比较字段的值不能为空", compareFeild, checkVal, TIMELINESS));
            return Collections.unmodifiableSet(errors);
        }
        //不做有效性检查
        try {
            String compareVal = compareNode.asText();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date parse = dateFormat.parse(checkVal);
            long dataTs = parse.getTime();
            Date compareparse = dateFormat.parse(compareVal);
            long compareTs = compareparse.getTime();
            double cha = compareTs - dataTs;
            //double result = cha * 1.0 / (1000 * 60 * 60);
            long startCheckTime = 0 - mistakeTime;
            long endCheckTime = expireTime * 1000 * 60 * 60 + mistakeTime;
            if (cha > startCheckTime && cha <= endCheckTime) {
                //未过期数据
                valid = true;
            }

            if (!valid) {
                errors.add(buildValidationMessage(at, "数据过期",compareFeild, checkVal, TIMELINESS));
            }
            return Collections.unmodifiableSet(errors);
        }catch (Exception ex){
            errors.add(buildValidationMessage(at, "过期检查中出现错误："+ex.getMessage(), compareFeild, checkVal, TIMELINESS));
            return Collections.unmodifiableSet(errors);
        }
    }

    public static void main(String[] args) {
        String s = "city_ts,24,3600000";
        String[] arr = s.split(",");
        System.out.println(arr[0]);
    }
}
